'use strict'

import { app, protocol, BrowserWindow, ipcMain, Tray, Menu, screen, globalShortcut, dialog } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
import {setDefaultProtocol,watchProtocol} from './mainPro/protocol'
import {setTray} from './mainPro/tray.js'
const isDevelopment = process.env.NODE_ENV !== 'production'
const path = require('path');
const iconPath = path.join(__static, 'logo.png');
let tray;
let remindWindow;
let mainWindow;
let remindFlag = true
const getTheLock = app.requestSingleInstanceLock();
if (!getTheLock) {
    app.quit()
}
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    //frame: false,
    //resizable: false,
    webPreferences: {
      // nodeIntegration: true,
      // enableRemoteModule: true,
      // contextIsolation: false
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    mainWindow.loadURL('app://./index.html')
  }
  //mainWindow.removeMenu();
  // 注册快捷键
  globalShortcut.register('CommandOrControl+Shift+R', () => {
    console.log('触发命令')
    mainWindow.webContents.send("StartRecording")
  })
  globalShortcut.register('CommandOrControl+Shift+S', () => {
    const path = app.getPath("downloads")
    mainWindow.webContents.send("StopRecording", path)
  })
  setTray(mainWindow);
  //setMenu();
  //setMenuForRole();
  visibleMenu();
  setDefaultProtocol();
  watchProtocol();
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
// 卸载命令
app.on('will-quit', () => {
  globalShortcut.unregisterAll();
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  // 跳过安装加快启动速度
  // if (isDevelopment && !process.env.IS_TEST) {

  //   try {
  //     await installExtension(VUEJS3_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
// 监听进程
ipcMain.on('mainWindow:close', () => {
  mainWindow.hide()
})

ipcMain.on('remindWindow:close', () => {
  remindWindow.close()
})

ipcMain.on('setTaskTimer', (event, time, task) => {
  const now = new Date()
  const date = new Date()
  date.setHours(time.slice(0, 2), time.slice(3), 0)
  const timeout = date.getTime() - now.getTime()
  setTimeout(() => {
    createRemindWindow(task)
  }, timeout)
})

// 设置系统托盘


// 创建子窗口
function createRemindWindow(task) {
  if (!remindFlag) {
    remindWindow.close()
  }
  remindWindow = new BrowserWindow({
    height: 450,
    width: 360,
    resizable: false,
    //frame: false,
    icon: iconPath,
    show: false,
    webPreferences: {

      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: true,
      enableRemoteModule: true,
      contextIsolation: false
    }
  })
  //remindWindow.removeMenu();
  remindFlag = false
  // 计算窗口弹出的位置
  // 获取屏幕尺寸
  const size = screen.getPrimaryDisplay().workAreaSize;
  // 获取托盘位置的y坐标（windows在右下角 mac在右上角）
  const { y } = tray.getBounds();
  // 获取窗口的宽高
  const { height, width } = remindWindow.getBounds();
  // 计算窗口的Y坐标
  const yPosition = process.platform === 'darwin' ? y : y - height
  // 设置窗口的位置
  remindWindow.setBounds({
    X: width,
    y: yPosition,
    height,
    width
  })
  //当有多个应用时，提醒窗口始终处于最上层
  remindWindow.setAlwaysOnTop(true)
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    remindWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL + '/remind.html')
  } else {
    createProtocol('app')
    remindWindow.loadURL(`file://${__dirname}/remind.html`)
  }
  // 
  remindWindow.show();

  // 主进程通知子进程 这里是main进程通知了remind渲染进程
  remindWindow.webContents.on('did-finish-load', () => {
    remindWindow.webContents.send('setTask', task)
  })
  remindWindow.on('close', function () {
    remindFlag = true
  })
}
// 设置窗口菜单
function setMenu() {
  const template = [
    {
      label: 'app',
      submenu: [
        { label: '退出', click: () => { app.quit() } },
        { label: "关于", click: () => { app.showAboutPanel() } }
      ]
    },
    {
      label: '文件',
      submenu: [
        {
          label: '子菜单',
          click: () => {
            dialog.showMessageBoxSync({
              type: 'info',
              title: '提示',
              message: '点击了子菜单'
            })
          }
        }
      ]
    }
  ]
  const menu = Menu.buildFromTemplate(template);

  Menu.setApplicationMenu(menu)
}
// 创建上下文菜单未生效 ROle
ipcMain.on('show-context-menu', (event) => {
  const template = [
    {
      label: "app",
      submenu: [
        { role: "quit" },
        { role: 'about' }
      ]
    },
    {
      label: "编辑",
      role: 'editMenu'
    }
  ]
  const contextMenu = Menu.buildFromTemplate(template);
  // BrowserWindow 还是个自带方法对象的函数
  contextMenu.popup(BrowserWindow.fromWebContents(event.sender))
})
// 设置窗口菜单Role版本
function setMenuForRole() {
  const templateCustom = [
    {
      label: 'app', // macOS下第一个标签是应用程序名字，此处设置无效
      submenu: [
        { label: 'quit', role: 'quit' },
        { label: '关于', role: 'about', accelerator: 'CommandOrControl + shift + H' }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { role: 'editMenu' },
        { type: 'separator' },
        {
          label: '自定义', click: () => {
            const win = new BrowserWindow()
            win.loadURL('https://electronjs.org')
          }
        }
      ]
    }
  ]

  const customMenu = Menu.buildFromTemplate(templateCustom)

  Menu.setApplicationMenu(customMenu)
}
// 隐藏菜单窗口
function visibleMenu() {
  const menu = Menu.getApplicationMenu();
  //console.log(menu.items[2].submenu.items, '打印菜单')
  menu.items[2].submenu.items[2].visible = false
}
/* 音乐播放器的进程 应该可以拆分出去 */
let filePth;
// windows通过process.argv获取打开文件的路径
if (process.platform === 'win32') {
  filePth = process.argv[1];
}
// Mac监听open-file事件 获取打开文件的路径
app.on('open-file', (event, path) => {
  filePth = path;
})

// 监听渲染进程的获取路径要求 把路径消息返回给渲染进程
ipcMain.on("getPath", () => {
  mainWindow.webContents.send("path", filePth); //发送给渲染进程
})
